package vip.xiaonuo.app.modular.pay.controller.front;

import cn.hutool.log.Log;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.app.core.consts.AppConstant;
import vip.xiaonuo.app.modular.pay.entity.AppAlipayConfig;
import vip.xiaonuo.app.modular.pay.param.front.ApiTradePayParam;
import vip.xiaonuo.app.modular.pay.result.PayInfoResult;
import vip.xiaonuo.app.modular.pay.service.AppAlipayConfigService;
import vip.xiaonuo.app.modular.recharge.service.AppRechargeOrderService;
import vip.xiaonuo.app.modular.vip.service.AppVipOrderService;
import vip.xiaonuo.core.pojo.response.ResponseData;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>Title : </p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows11</p>
 *
 * @Author : zxw
 * @Date 2023/10/8 11:16
 */
@RestController
@RequestMapping("/api/aliPayVersion3")
public class ApiAliPayConfigController {

    private static final Log log = Log.get();

    @Resource
    private AppAlipayConfigService appAlipayConfigService;
    @Resource
    private AppRechargeOrderService appRechargeOrderService;
    @Resource
    private AppVipOrderService appVipOrderService;


    /**
     * H5统一下单接口
     *
     * @return
     */
    @PostMapping("/tradeWapPay")
    public ResponseData tradeWapPay(@RequestBody ApiTradePayParam param) {
        PayInfoResult result =
                appAlipayConfigService.tradeWapPay(
                        param.getUserId(),
                        param.getMobileSpec(),
                        param.getProjectType(),
                        param.getPackageId(),
                        param.getMoney());
        return ResponseData.success(result);
    }

    /**
     * 支付回调
     */
    @PostMapping("/notifyUrl/{appIdStr}/{project}")
    public void notifyUrl(HttpServletRequest request, @PathVariable("appIdStr") String appIdStr, @PathVariable("project") Integer project) {
        System.out.println(appIdStr + ":" + project);
        //获取对应的支付商户信息
        AppAlipayConfig info = appAlipayConfigService.getByAppId(appIdStr);
        //通过appId获取对应账号信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, info.getAppPublicKey(), info.getCharset(), info.getSignType());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("验证公钥时出现异常");
        } // 调用SDK验证签名
        log.info("验证签名结果" + signVerified);
        //对应数据库操作
        if (signVerified) {
            // 商户订单号
            String out_trade_no = null;
            String trade_no = null;
            String trade_status = null;
            try {
                // 商户订单号
                out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                // 支付宝交易号
                trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
                // 交易状态
                trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            log.info("-----------商户订单号" + out_trade_no);
            log.info("-----------支付宝交易号" + trade_no);
            log.info("-----------交易状态" + trade_status);
            //订单支付成功
            if ("TRADE_SUCCESS".equals(trade_status)) {
                //根据订单号、支付状态、支付方式获取预订单 执行入库操作
                if (project.equals(AppConstant.PAY_PROJECT_DO)) {
                    appRechargeOrderService.successCallBack(out_trade_no, trade_no);
                } else if (project.equals(AppConstant.PAY_PROJECT_VIP)) {
                    appVipOrderService.successCallBack(out_trade_no, trade_no);
                }
            }
            log.info("支付宝回调成功，充值入账成功");
        }
    }

}
